package com.cpkso.buss.backend.user.domain;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.Index;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.Table;

import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;

import com.runze.base.domain.RecordEntity;

/**
 * 角色类
 * @author wrzhxy@qq.com
 * @date 2018年3月13日
 */
@Entity
@Table(name="role", indexes = {@Index(name="idx_roles_name", columnList="name")})
@Cache(usage= CacheConcurrencyStrategy.READ_WRITE)
public class Role extends RecordEntity {
	/**
	 * 角色名称
	 */
    @Basic(optional=false)
    @Column(unique=true)
	private String name;
	/**
	 * 角色描述
	 */
	private String description;
    /**
     * 多对多 权限
     */
	@ManyToMany(fetch=FetchType.LAZY)
	@JoinTable(name="role_permission", 
		joinColumns=@JoinColumn(name="rid", foreignKey=@ForeignKey(name = "FK_rp_role")),
		inverseJoinColumns=@JoinColumn(name="pid", foreignKey=@ForeignKey(name = "FK_rp_permission")))
	@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
	private Set<Permission> permissions = new HashSet<>();
	
	/**
	 * 多对多 用户
	 */
	@ManyToMany(fetch=FetchType.LAZY, mappedBy="roles")
	@Cache(usage=CacheConcurrencyStrategy.READ_WRITE)
	private Set<User> users = new HashSet<>();
	
	public Role() {
	}
	public Role(String name, Set<Permission> permissions) {
		this.name = name;
		this.permissions = permissions;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getDescription() {
		return description;
	}
	public void setDescription(String description) {
		this.description = description;
	}
	public Set<Permission> getPermissions() {
		return permissions;
	}
	public void setPermissions(Set<Permission> permissions) {
		this.permissions = permissions;
	}
	public void addPermission(Permission permission) {
		permissions.add(permission);
	}
	public void removePermission(Permission permission) {
		permissions.remove(permission);
	}
	public Set<User> getUsers() {
		return users;
	}
	public void setUsers(Set<User> users) {
		this.users = users;
	}
	
	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((id == null) ? 0 : id.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Role other = (Role) obj;
		if (id == null) {
			if (other.id != null)
				return false;
		} else if (!id.equals(other.id))
			return false;
		return true;
	}
}
